import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CommonService } from '../../../../services-common/common.service';
import { DatePipe } from '@angular/common';
import { format, subDays } from 'date-fns';
import { forkJoin } from 'rxjs';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { UnionPayManageService } from '../unionPay-manage.service';

@Component({
  selector: 'app-cooperation-unionpay-statistics',
  templateUrl: './cooperation-unionpay-statistics.component.html',
  styleUrls: ['./cooperation-unionpay-statistics.component.scss'],
  providers: [DatePipe]
})
export class CooperationUnionpayStatisticsComponent implements OnInit {

  searchOptions = [
    { type: 1, labelText: '综合搜索', valueKey: 'mchSearch', value: '', placeholder: '商户名/商户ID' },
    { type: 1, labelText: '所属拓展员', valueKey: 'userId', value: '', placeholder: 'ID' }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  statisticsObjs: any = {
    totalAmount: 0,
    totalIncome: 0
  };

  /**
   * 新增 Modal
   * ----------------------------------------------------------------
   */
  isFlowWaterVisible = false;
  validateForm!: FormGroup;
  subWaterLoading = false;

  /**
   * 查看明细 Modal
   * ----------------------------------------------------------------
   */
  isDetailedVisible = false;
  detailedItem: any = {};
  detailedTableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  merchantOptions: any[] = []; // 商户Options
  adminOptions: any[] = []; // 管理员Options

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private commonService: CommonService,
    private services: UnionPayManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userId: ['', [Validators.required]],
      mchId: ['', [Validators.required]],
      date: ['', [Validators.required]],
      amount: ['', [Validators.required]],
      income: ['', [Validators.required]]
    });
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getFlowwaterList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      const { list } = data || {};
      this.tableParams.tableData = list.records || [];
      this.tableParams.total = list.total || 0;

      for (let key in this.statisticsObjs) {
        this.statisticsObjs[key] = data[key] || 0;
      }
    } else {
      this.msg.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  timeChange(val: any) {
    let tm = val ? this.datePipe.transform(val, 'yyyy-MM-dd') : '';
    this.validateForm.get('date')?.setValue(tm);
  }

  waterChange(val: any) {
    let newVal = val * 0.001;
    this.validateForm.patchValue({
      income: val ? Math.floor(newVal * 100) / 100 : ''
    })
  }

  adminChange(val: any) {
    this.validateForm.get('mchId')?.setValue('');

    if (!this.commonService.isEmpty(val)) {
      this.loadMerchantOptions();
    }
  }

  /**
   * ----------------------------------------------------------------
   * 新增流水
   * ----------------------------------------------------------------
   */
  // 获取拓展员options
  async loadAdminOptions() {
    const {code, data, message}: any = await this.services.getAdminOptionData();
    if (code === 0) {
      this.adminOptions = data || [];
    } else {
      this.msg.error(message);
    }
  }

  // 获取商户options
  async loadMerchantOptions() {
    const {code, data, message}: any = await this.services.getMerchantOptionData(this.validateForm.value.userId);
    if (code === 0) {
      this.merchantOptions = data || [];
    } else {
      this.msg.error(message);
    }
  }

  showExamineModal() {
    this.validateForm.reset();
    this.loadAdminOptions();

    let timeAgo = subDays(new Date(), 1);
    this.validateForm.get('date')?.setValue(timeAgo ? format(timeAgo, 'yyyy-MM-dd') : '');
    this.isFlowWaterVisible = true;
  }

  async submitForm() {
    if (this.validateForm.valid) {
      let mchTempObj = this.merchantOptions.find(item => item.id === this.validateForm.value.mchId);
      let userTempObj = this.adminOptions.find(item => item.id === this.validateForm.value.userId);
      let params = {
        ...this.validateForm.value,
        mchName: mchTempObj?.mchName || '',
        userName: userTempObj?.userName || ''
      }
      
      this.subWaterLoading = true;
      const {code, message}: any = await this.services.addFlowwaterData(params);
      this.subWaterLoading = false;

      if (code === 0) {
        this.isFlowWaterVisible = false;
        this.msg.success('操作成功');
        this.loadTable();
      } else {
        this.msg.error(message);
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 查看明细
   * ----------------------------------------------------------------
   */
  async loadDetailedTable() {
    let params = {
      id: this.detailedItem.id,
      page: this.detailedTableParams.page,
      pageSize: this.detailedTableParams.pageSize
    }
    this.detailedTableParams.loading = true;
    const {code, data, message}: any = await this.services.getFlowwaterDetails(params);
    this.detailedTableParams.loading = false;

    if (code === 0) {
      this.detailedTableParams.tableData = data.records || [];
      this.detailedTableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  showDetailedModal(item: any) {
    this.detailedItem = item;

    this.loadDetailedTable();
    this.isDetailedVisible = true;
  }
 
  // PageIndex Change
  onModalPageIndexChanget(index: number) {
    this.detailedTableParams.page = index;
    this.loadDetailedTable();
  }
 
  // PageSize Change
  onModalPageSizeChange(sizeNum: number) {
    this.detailedTableParams.page = 1;
    this.detailedTableParams.pageSize = sizeNum;
    this.loadDetailedTable();
  }
}
